/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AddOrderingDialog.java
 *
 * Created on Apr 3, 2011, 1:55:23 AM
 */

package client;

import java.util.ArrayList;
import java.util.Calendar;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;
import org.workplicity.inventorycontrol.entry.Inventory;
import org.workplicity.inventorycontrol.entry.Item;
import org.workplicity.util.Helper;
import org.workplicity.util.WorkDate;
import org.workplicity.inventorycontrol.entry.OrderAudit;
import org.workplicity.util.DateFormatter;
import org.workplicity.worklet.WorkletContext;

/**
 *
 * @author SandeepMJ
 */
public class AddOrderingDialog extends javax.swing.JDialog {

    private ArrayList<OrderAudit> currentOrder = new ArrayList<OrderAudit>( );
    private ArrayList<Inventory> currentInventory = new ArrayList<Inventory>( );
    private ArrayList<Item> currentItem = new ArrayList<Item>( );

    /** Creates new form AddOrderingDialog */
    public AddOrderingDialog(java.awt.Frame parent,Inventory inventory, Item item, OrderAudit order, boolean modal) {
        super(parent, modal);
        initComponents();

        try {
                javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
            } catch (Exception e) {

            }
        this.setLocationRelativeTo(null);

        currentInventory.add(inventory);
        currentItem.add(item);
        currentOrder.add(order);

        if (order.getId() == -1 )
        {
            this.setTitle("Add new order");
        }else{
            this.setTitle("Edit order");
        }

        // custom initialization for add order.
        init(order);
    }

    private void init(OrderAudit order){

        if (!( order.getStamp() == null)){

            String orderDate = DateFormatter.toString(order.getStamp());
            orderingDateTextField.setText(orderDate);
        }
        else
        {
            Calendar calendar = Calendar.getInstance();

            String orderDate = DateFormatter.toString(calendar.getTime());

            orderingDateTextField.setText(orderDate);

        }

        if (!( order.getOrdersize() == null)){
            sizeTextField.setText(order.getOrdersize().toString());
        }
        if (! (order.getPoNumber() == null)){
            poNumberTextField.setText(order.getPoNumber().toString());
        }
        if (! (order.getOrderNumber() == null)){
            orderNumberTextField.setText(order.getOrderNumber().toString());
        }
       

    }


    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        calendarButton = new javax.swing.JButton();
        orderingDateTextField = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();
        sizeTextField = new javax.swing.JTextField();
        cancelButton = new javax.swing.JButton();
        poNumberTextField = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        orderNumberTextField = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setName("Form"); // NOI18N

        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(client.MainFrame.class).getContext().getResourceMap(AddOrderingDialog.class);
        calendarButton.setIcon(resourceMap.getIcon("calendarButton.icon")); // NOI18N
        calendarButton.setName("calendarButton"); // NOI18N
        calendarButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                calendarButtonActionPerformed(evt);
            }
        });

        orderingDateTextField.setEditable(false);
        orderingDateTextField.setText(resourceMap.getString("orderingDateTextField.text")); // NOI18N
        orderingDateTextField.setName("orderingDateTextField"); // NOI18N
        orderingDateTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                orderingDateTextFieldActionPerformed(evt);
            }
        });

        jLabel2.setText(resourceMap.getString("jLabel2.text")); // NOI18N
        jLabel2.setName("jLabel2"); // NOI18N

        saveButton.setText(resourceMap.getString("saveButton.text")); // NOI18N
        saveButton.setName("saveButton"); // NOI18N
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        sizeTextField.setText(resourceMap.getString("sizeTextField.text")); // NOI18N
        sizeTextField.setName("sizeTextField"); // NOI18N
        sizeTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sizeTextFieldActionPerformed(evt);
            }
        });

        cancelButton.setText(resourceMap.getString("cancelButton.text")); // NOI18N
        cancelButton.setName("cancelButton"); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });

        poNumberTextField.setText(resourceMap.getString("poNumberTextField.text")); // NOI18N
        poNumberTextField.setName("poNumberTextField"); // NOI18N

        jLabel4.setText(resourceMap.getString("jLabel4.text")); // NOI18N
        jLabel4.setName("jLabel4"); // NOI18N

        jLabel3.setText(resourceMap.getString("jLabel3.text")); // NOI18N
        jLabel3.setName("jLabel3"); // NOI18N

        orderNumberTextField.setText(resourceMap.getString("orderNumberTextField.text")); // NOI18N
        orderNumberTextField.setName("orderNumberTextField"); // NOI18N

        jLabel5.setText(resourceMap.getString("jLabel5.text")); // NOI18N
        jLabel5.setName("jLabel5"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel4)
                            .addComponent(jLabel3)
                            .addComponent(jLabel2)
                            .addComponent(jLabel5))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(poNumberTextField)
                                    .addComponent(orderingDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 122, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(sizeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(calendarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(orderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 77, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(61, 61, 61))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 154, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(saveButton)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cancelButton)))
                .addContainerGap(18, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(orderingDateTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(calendarButton))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(sizeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(poNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(orderNumberTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(9, 9, 9)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveButton)
                    .addComponent(cancelButton))
                .addContainerGap(22, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void orderingDateTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_orderingDateTextFieldActionPerformed
        // TODO add your handling code here:
}//GEN-LAST:event_orderingDateTextFieldActionPerformed

    private void sizeTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sizeTextFieldActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_sizeTextFieldActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
       
        String orderDate = orderingDateTextField.getText().toString();
        String size = sizeTextField.getText().toString();
        String poNumber = poNumberTextField.getText().toString();
        String orderNumber = orderNumberTextField.getText().toString();

        Integer orderSize = 0;

        OrderAudit newOrder = currentOrder.get(0);

        String errorMessage = "";
        // validates the user entries in the text fields and combo boxes.
        if(orderDate.equals("")  || orderDate.isEmpty())
        {
            errorMessage += "Please select a order date.\n";

        }

        if ((size.equals("")) || size.equals("Enter size") || size.isEmpty())
        {
            errorMessage += "Please enter order size.\n";

        }

        try{
            orderSize = Integer.parseInt(size);
        }catch(Exception ex){
            errorMessage += "Order size must be a positive integer value.\n";
        }

        if(poNumber.equals("") || poNumber.equals("Enter PO #") || poNumber.isEmpty())
        {
            errorMessage += "Please enter PO number.\n";

        }

        if (orderNumber.equals("") || orderNumber.equals("Enter order #") || orderNumber.isEmpty())
        {
            errorMessage += "Please enter order name.\n";
        }

        if(errorMessage.length() > 0) {

            JOptionPane.showMessageDialog(this,errorMessage,
                                        "Required parameters missing",
                                        JOptionPane.ERROR_MESSAGE);
        }
        else
        {
            WorkDate date = Helper.toDate(orderingDateTextField.getText());

            newOrder.setStamp(date);
            newOrder.setOrdersize(orderSize);
            newOrder.setPoNumber(poNumber);
            newOrder.setOrderNumber(orderNumber);

            insertOrder(newOrder);

            dispose();
        }

    }//GEN-LAST:event_saveButtonActionPerformed


   /** This method inserts the order passed into the order repository.
     * The method also included the order in the item order list and updates the item.
     */
    private void insertOrder(OrderAudit newOrder){

        final AddOrderingDialog frame = this;
        WorkletContext context = WorkletContext.getInstance();
        Item item = currentItem.get(0);
        Inventory inventory = currentInventory.get(0);

        System.out.println(newOrder.getId());

         if (!Helper.insert(newOrder, "Orders", context)) {
             JOptionPane.showMessageDialog(frame, "insert order into orders failed!",
                "Orders", JOptionPane.ERROR_MESSAGE);

             return;
         }// end if

         System.out.println(newOrder.getId());

         int orderID = newOrder.getId();
         boolean trainingExists = false;

         //gets the items order history array list.
         // checks if the order is already present in it.
         // if it is not present it adds the new order to the item order list.
         // and inserts new order to orders repository.
         // if it exisits it proceeds to update the existing order
         if(!(item.getOrderHistory().isEmpty() ))
         {
            for(int i=0; i < item.getOrderHistory().size();i++)
            {
                int itemOrderID = item.getOrderHistory().get(i).getId();

                if ((itemOrderID == orderID))
                {
                    trainingExists = true;
                }// end if

            }// end for
         }// end if

         if(!(trainingExists))
         {
            ArrayList<OrderAudit> itemOrders = item.getOrderHistory();

            itemOrders.add(newOrder);

            item.setOrderHistory(itemOrders);

            inventory.insert(item);

            System.out.println(item.getId());

            if (!Helper.insert(item, "Inventories", context)) {
                System.out.println("insert Item into Inventory failed!");

            }

            System.out.println(item.getId());

         }
        
     }

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        // TODO add your handling code here:
         dispose();
    }//GEN-LAST:event_cancelButtonActionPerformed

    private void calendarButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_calendarButtonActionPerformed
        // TODO add your handling code here:
        final AddOrderingDialog dialog = this;
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                WorkDate date = Helper.toDate(orderingDateTextField.getText());

                // displays calendar dialog
                CalendarDialog calendar = new CalendarDialog(dialog,date);

                calendar.setVisible(true);
                if(calendar.getCalendar() == null)
                    return;

                int year = calendar.getCalendar().get(Calendar.YEAR);
                int mon = calendar.getCalendar().get(Calendar.MONTH) + 1;
                int day = calendar.getCalendar().get(Calendar.DAY_OF_MONTH);

                String mons = mon < 10 ? "0"+mon : mon+"";
                String days = day < 10 ? "0"+day : day+"";

                // displays date in the text field in mm/dd/yy
                dialog.orderingDateTextField.setText(mons + " / " + days + " / "+year);

            }
        });
    }//GEN-LAST:event_calendarButtonActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                // Attempt to set the appearance to the system default
                try {
                    javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());
                } catch (Exception e) {

                }
                AddOrderingDialog dialog = new AddOrderingDialog(new javax.swing.JFrame(),null, null, null, true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton calendarButton;
    private javax.swing.JButton cancelButton;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JTextField orderNumberTextField;
    private javax.swing.JTextField orderingDateTextField;
    private javax.swing.JTextField poNumberTextField;
    private javax.swing.JButton saveButton;
    private javax.swing.JTextField sizeTextField;
    // End of variables declaration//GEN-END:variables

}
